package cn.com.note.activity;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.StringUtils;

import java.util.Map;

import cn.com.note.R;
import cn.com.note.utils.LoginFileUtils;

/**
 * Created by sunfulin on 2019/2/11.
 */

public class LoginTxtActivity extends AppCompatActivity implements View.OnClickListener {
    EditText account, passWord;
    Button btLogin, btWrite;
    Map<String, String> userInfo;
    CheckBox passCheckBox;
    Context context;
    TextView tvInfo;
    /**
     * 是否是assets 下的 txt 文件 不允许编辑所以，需要在sd卡下操作
     */
    private final static boolean IS＿FROM_ASSETS = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_txt);
        context = this;
        account = findViewById(R.id.user_name);
        passWord = findViewById(R.id.pass_word);
        btLogin = findViewById(R.id.login_bnt);
        btWrite = findViewById(R.id.bt_write);
        passCheckBox = findViewById(R.id.passCheckBox);
        tvInfo = findViewById(R.id.tvInfo);
        tvInfo.setMovementMethod(ScrollingMovementMethod.getInstance());
        passCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    //从密码不可见模式变为密码可见模式
                    passWord.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    //从密码可见模式变为密码不可见模式
                    passWord.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                passWord.setSelection(passWord.getText().length());
            }
        });
        btLogin.setOnClickListener(this);
        btWrite.setOnClickListener(this);
        findViewById(R.id.bt_look_info).setOnClickListener(this);
        findViewById(R.id.modify_pass).setOnClickListener(this);
        //判断本地是否已经有文件，如果没有，创建文件
        createFile();
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (IS＿FROM_ASSETS) {
                    userInfo = LoginFileUtils.readFromAssets(context, "userInfo.txt");
                } else {
                    userInfo = LoginFileUtils.readFromSDCard("/userInfo.txt");
                }
            }
        }).start();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login_bnt:
                verificationAccountAndPassword();
                break;
            case R.id.bt_write:
                writeAccountAndPassword();
                break;
            case R.id.bt_look_info:
                analysisMap();
                break;
            case R.id.modify_pass:
                modifyPassWord();
                break;
            default:
                break;
        }

    }

    /**
     * 修改密码
     */
    private void modifyPassWord(){
        if (StringUtils.isEmpty(account.getText())) {
            Toast.makeText(context, "请输入账号！", Toast.LENGTH_SHORT).show();
            return;
        }
        if (StringUtils.isEmpty(passWord.getText())) {
            Toast.makeText(context, "请输入密码！", Toast.LENGTH_SHORT).show();
            return;
        }
        String userName = account.getText().toString().trim();
        String userPass = passWord.getText().toString().trim();
        userInfo.put(userName,userPass);
        //修改 txt 文件内容
        LoginFileUtils.modifyPassFromSDCard("/userInfo.txt",userInfo);
    }


    private void analysisMap() {
        if (userInfo == null)
            return;
        //遍历map中的键
        String result = "";
        for (String key : userInfo.keySet()) {
            result += "账号：" + key + "  密码：" + userInfo.get(key) + "\n";
        }
        tvInfo.setText(result);
        tvInfo.setVisibility(View.VISIBLE);
    }

    /**
     * sd卡中的txt写入账号和密码
     */
    private void writeAccountAndPassword() {
        if (StringUtils.isEmpty(account.getText())) {
            Toast.makeText(context, "请输入账号！", Toast.LENGTH_SHORT).show();
            return;
        }
        if (StringUtils.isEmpty(passWord.getText())) {
            Toast.makeText(context, "请输入密码！", Toast.LENGTH_SHORT).show();
            return;
        }
        String userName = account.getText().toString().trim();
        String userPass = passWord.getText().toString().trim();

        if (userInfo.containsKey(userName)) {
            Toast.makeText(context, "账号已存在！", Toast.LENGTH_SHORT).show();
        } else {
            boolean isSuccess;
            if (IS＿FROM_ASSETS) {
                isSuccess = LoginFileUtils.saveAccountAndPassWordToAssets(userName, userPass, "userInfo.txt");
            } else {
                isSuccess = LoginFileUtils.saveAccountAndPassWordToFile(userName, userPass, "/userInfo.txt");
            }
            if (isSuccess) {
                Toast.makeText(context, "写入成功！", Toast.LENGTH_SHORT).show();
                userInfo.put(userName, userPass);
            } else {
                Toast.makeText(context, "写入失败！", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 通过本地txt文件
     * 验证账号密码
     */
    private void verificationAccountAndPassword() {
        if (StringUtils.isEmpty(account.getText())) {
            Toast.makeText(context, "请输入账号！", Toast.LENGTH_SHORT).show();
            return;
        }
        if (StringUtils.isEmpty(passWord.getText())) {
            Toast.makeText(context, "请输入密码！", Toast.LENGTH_SHORT).show();
            return;
        }
        String userName = account.getText().toString().trim();
        String userPass = passWord.getText().toString().trim();
        if (userInfo.containsKey(userName)) {
            if (userPass.equals(userInfo.get(userName).toString().trim())) {
                Toast.makeText(context, "登录成功！", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(context, "密码错误！", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(context, "账号不存在！", Toast.LENGTH_SHORT).show();
        }
    }


    private void createFile() {
        //String path = LoginFileUtils.rootPath+"/账号";
        //FileUtils.createOrExistsDir(path);//创建目录
        FileUtils.createOrExistsFile(LoginFileUtils.rootPath + "/userInfo.txt");//创建文件
    }


}
